package com.shankungfu.main;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.PersistentCookieStore;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.shankungfu.GlobleConstant;
import com.shankungfu.MainApplication;
import com.shankungfu.R;
import com.shankungfu.adapter.MyPagerAdapter;
import com.shankungfu.adapter.UserListlAdapter;
import com.shankungfu.bean.InterestDataBean;
import com.shankungfu.bean.MyInterestDataBean;
import com.shankungfu.bean.UserBean;
import com.shankungfu.util.MyAsyncHttpResponseHandler;
import com.shankungfu.util.ToastUtil;
import com.shankungfu.util.WebService;
import com.shankungfu.view.CustomDialog;
import com.shankungfu.view.CustomDialog.Builder;

public class UserCenterActivity extends Activity implements OnClickListener {

	public static final String USER_CATEGORY = "user_category";
	public static final int FAQI = 0;
	public static final int CANJIA = 2;
	public static final int GANXINGQU = 1;
	private static final int DATE_SUCCESS = 3;
	private static final int DATA_FAILE = 4;
	private static final int DATA_EMTY = 5;

	private TextView volunteer_time;
	private TextView username;
	private TextView grade;
	private ImageView user_img;
	private ImageLoader imageLoader;
	private ViewPager viewpager;
	private int category;
	private UserBean userBean;
	private UserListlAdapter adapter;
	private ListView[] listViews = new ListView[3];
	private UserListlAdapter[] adapters = new UserListlAdapter[3];
	private View[] loadMoreViews = new View[3];
	private Button[] loadMoreButtons = new Button[3];
	private ProgressBar[] loadMoreProgressBars = new ProgressBar[3];
	private ArrayList<View> pagesArrayList;
	private LayoutInflater mInflater;
	private int join_pagesize = 1;
	private int interest_pagesize = 1;
	private int lead_pagesize = 1;
	private int[] pagesizes = new int[]{lead_pagesize, join_pagesize, interest_pagesize};
	private int visibleLastIndex = 0; // 最后的可视项索引
	private int visibleItemCount; // 当前窗口可见项总数
	private List<MyInterestDataBean> list;

	private ImageView imageView;// 动画图片
	private int offset = 0;// 动画图片偏移量
	private int currIndex = 0;// 当前页卡编号
	private int bmpW;// 动画图片宽度
	
	private boolean lead_flag = true;
	private boolean interest_flag = true;
	private boolean join_flag = true;

	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);

			switch (msg.what) {
			case DATE_SUCCESS:
				InterestDataBean detailBean = (InterestDataBean) msg.obj;
				showDataSuccess(viewpager.getCurrentItem(), detailBean);
				break;
				
			case DATA_FAILE:
				showDataFaile(viewpager.getCurrentItem());
				
				ToastUtil.showMessageText(UserCenterActivity.this, "数据加载异常");
				
				break;
			case DATA_EMTY:
				showDataEmpty(viewpager.getCurrentItem());
				
				break;
			}
		}
	};
	private Button my_sponsor;
	private Button my_interest;
	private Button my_join;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.user_center_layout);

		initImageView();
		init();
		data();
	}

	private void init() {
		mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

		category = getIntent().getIntExtra(USER_CATEGORY, 0);

		userBean = MainApplication.userBean;

		TextView title = (TextView) findViewById(R.id.detail_title);
		title.setText("个人中心");

		ImageView logOut = (ImageView) findViewById(R.id.head_refresh);
		logOut.setImageResource(R.drawable.logout_head_bg);

		user_img = (ImageView) findViewById(R.id.user_icon);
		username = (TextView) findViewById(R.id.username);
		grade = (TextView) findViewById(R.id.grade);
		volunteer_time = (TextView) findViewById(R.id.volunteer_time);

		my_sponsor = (Button) findViewById(R.id.my_sponsor);
		my_join = (Button) findViewById(R.id.my_join);
		my_interest = (Button) findViewById(R.id.my_interest);

		pagesArrayList = new ArrayList<View>();
		imageLoader = ImageLoader.getInstance();

		username.setText(userBean.getLoginData().getUser_name());
		grade.setText("善功夫等级：" + userBean.getLoginData().getUser_grade());
		volunteer_time.setText("志愿时："
				+ userBean.getLoginData().getUser_services_time() + "小时");

		imageLoader.displayImage(userBean.getLoginData().getAtatar_url(),
				user_img, MainApplication.getOptions(), null);

		viewpager = (ViewPager) findViewById(R.id.user_center_viewpager);

		for (int i = 0; i < 3; i++) {
			
			loadMoreViews[i] = mInflater.inflate(R.layout.loadmore_layout, null, false);
			loadMoreButtons[i] = (Button) loadMoreViews[i].findViewById(R.id.loadmore_btn);
			loadMoreProgressBars[i] = (ProgressBar) loadMoreViews[i]
					.findViewById(R.id.loadmore_progressbar);
			
			listViews[i] = (ListView) mInflater.inflate(
					R.layout.viewpager_listviewitem_layout, null, false)
					.findViewById(R.id.viewpager_listview);

			listViews[i].addFooterView(loadMoreViews[i]); // 设置列表底部视图

			adapters[i] = new UserListlAdapter(this,
					MainApplication.getOptions());

			adapter = adapters[i];

			listViews[i].setAdapter(adapter);
			
			pagesArrayList.add(listViews[i]);
		}

		viewpager.setAdapter(new MyPagerAdapter(pagesArrayList));
		viewpager.setOnPageChangeListener(new MyOnPageChangeListener());
	}

	/**
	 * 初始化动画，这个就是页卡滑动时，下面的横线也滑动的效果，在这里需要计算一些数据
	 */

	private void initImageView() {
		imageView = (ImageView) findViewById(R.id.iv_small);
		bmpW = BitmapFactory.decodeResource(getResources(),
				R.drawable.user_center_btn_bg).getWidth();// 获取图片宽度
		int screenW = MainApplication.screenWidth;// 获取分辨率宽度
		offset = (screenW / 3 - bmpW) / 2;// 计算偏移量
		Matrix matrix = new Matrix();
		matrix.postTranslate(offset, 0);
		imageView.setImageMatrix(matrix);// 设置动画初始位置
	}

	private void data() {
		switch (category) {

		case FAQI:// 我发起的
			getData("my_lead", GlobleConstant.MY_LEAD, lead_pagesize);
			my_sponsor.setTextColor(getResources().getColor(
					R.color.user_center_select_text));
			viewpager.setCurrentItem(FAQI);
			break;
		case CANJIA:// 我参加的
			getData("my_join", GlobleConstant.MY_JOIN, join_pagesize);
			my_join.setTextColor(getResources().getColor(
					R.color.user_center_select_text));
			viewpager.setCurrentItem(CANJIA);
			break;
		case GANXINGQU:// 我感兴趣的
			getData("my_interest", GlobleConstant.MY_INTEREST,
					interest_pagesize);
			my_interest.setTextColor(getResources().getColor(
					R.color.user_center_select_text));
			viewpager.setCurrentItem(GANXINGQU);
			break;

		}
	}

	private void getData(String serviceId, String url, int pagesize) {

		WebService httpclient = new WebService();
		RequestParams params = new RequestParams();
		params.add("serviceId", serviceId);
		params.add("user_Id", userBean.getLoginData().getUser_Id());
		params.add("page", String.valueOf(pagesize));

		AsyncHttpResponseHandler responseHandler = new MyAsyncHttpResponseHandler() {
			@Override
			public void onSuccess(String content) {
				if (!TextUtils.isEmpty(content)
						&& content.contains("\"result\":0")) {

					InterestDataBean activityBean = JSON.parseObject(content,
							InterestDataBean.class);

					Message msg = new Message();
					msg.what = DATE_SUCCESS;
					msg.obj = activityBean;
					handler.sendMessage(msg);
				} else {
					handler.sendEmptyMessage(DATA_EMTY);
				}
			}

			@Override
			public void onFailure(String content) {
				handler.sendEmptyMessage(DATA_FAILE);
			}
		};
		httpclient.request(url, params, responseHandler);
	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.head_goback:
			finish();
			break;
		case R.id.head_refresh:
			showLogoutDailog();
			break;
		case R.id.my_sponsor: // 我发起的
//			getData("my_lead", GlobleConstant.MY_LEAD, lead_pagesize);
			viewpager.setCurrentItem(FAQI);
			break;
		case R.id.my_join: // 我参加的
//			getData("my_join", GlobleConstant.MY_JOIN, join_pagesize);
			viewpager.setCurrentItem(CANJIA);
			break;
		case R.id.my_interest: // 我感兴趣的
//			getData("my_interest", GlobleConstant.MY_INTEREST,
//					interest_pagesize);
			viewpager.setCurrentItem(GANXINGQU);
			break;
		}

	}

	private void showLogoutDailog() {
		CustomDialog.Builder builder = new Builder(this);
		builder.setMessage("您确定要退出当前账户的登录吗?");
		builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				MainApplication.userBean = null;
				MainApplication.setUserIsLogin(false);
				PersistentCookieStore cookieStore = new PersistentCookieStore(
						MainApplication.context);
				cookieStore.clear();
				UserCenterActivity.this.finish();
			}
		});
		builder.create().show();
	}
	
	private void showDataSuccess(final int i,InterestDataBean detailBean){
		list = detailBean.getMyInterestData();
		if(detailBean.isNext()){
			adapters[i].addData(list);
			loadMoreButtons[i].setText("数据加载中...");
			listViews[i].setOnScrollListener(new OnScrollListener() {

				@Override
				public void onScrollStateChanged(AbsListView view,
						int scrollState) {
					int itemsLastIndex = adapters[i].getCount() - 1; // 数据集最后一项的索引
					int lastIndex = itemsLastIndex + 1; // 加上底部的loadMoreView项
					if (scrollState == OnScrollListener.SCROLL_STATE_IDLE
							&& visibleLastIndex == lastIndex) {
						// 如果是自动加载,可以在这里放置异步加载数据的代码
						// ++pagesize;
						switch (viewpager.getCurrentItem()) {
						case FAQI:
							++lead_pagesize;
							break;
						case GANXINGQU:
							++interest_pagesize;
							break;
						case CANJIA:
							++join_pagesize;
							break;
						default:
							break;
						}
						category = viewpager.getCurrentItem();
						data();
					}
				}

				@Override
				public void onScroll(AbsListView view, int firstVisibleItem,
						int visibleItemCount, int totalItemCount) {
					UserCenterActivity.this.visibleItemCount = visibleItemCount;
					visibleLastIndex = firstVisibleItem + visibleItemCount - 1;
				}
			}); // 添加滑动监听
//			listViews[i].setSelection(visibleLastIndex - visibleItemCount + 1);
		} else {

			adapters[i].addData(list);
			loadMoreButtons[i].setText("数据加载完毕");
			loadMoreProgressBars[i].setVisibility(View.GONE);
			listViews[i].setOnScrollListener(null);
		}

	}
	
	private void showDataFaile(int i){
		adapters[i].setData(list);
		loadMoreButtons[i].setText("数据失败");
		loadMoreProgressBars[i].setVisibility(View.GONE);
	}
	
	private void showDataEmpty(int i){
		loadMoreButtons[i].setText("没有更多项目了");
		loadMoreProgressBars[i].setVisibility(View.GONE);
	}

	class MyOnPageChangeListener implements OnPageChangeListener {
		int one = offset * 2 + bmpW;// 页卡1 -> 页卡2 偏移量
		int two = one * 2;// 页卡1 -> 页卡3 偏移量
		private int to;

		@Override
		public void onPageScrollStateChanged(int state) {
		}

		@Override
		public void onPageScrolled(int position, float positionOffset,
				int positionOffsetPixels) {
		}

		@Override
		public void onPageSelected(int position) {
			Animation animation = new TranslateAnimation(one * currIndex, one * position, 0, 0);// 显然这个比较简洁，只有一行代码。
			currIndex = position;
			animation.setFillAfter(true);// True:图片停在动画结束位置
			animation.setDuration(300);
			imageView.startAnimation(animation);

			switch (position) {
			case FAQI:
				my_sponsor.setTextColor(getResources().getColor(
						R.color.user_center_select_text));
				my_interest
						.setTextColor(getResources().getColor(R.color.white));
				my_join.setTextColor(getResources().getColor(R.color.white));

				if(lead_flag){
					getData("my_lead", GlobleConstant.MY_LEAD, lead_pagesize);
					lead_flag = false;
				}
				break;
			case CANJIA:
				my_sponsor.setTextColor(getResources().getColor(R.color.white));
				my_interest
						.setTextColor(getResources().getColor(R.color.white));
				my_join.setTextColor(getResources().getColor(
						R.color.user_center_select_text));

				if(join_flag){
					getData("my_join", GlobleConstant.MY_JOIN, join_pagesize);
					join_flag = false;
				}
				
				break;
			case GANXINGQU:
				my_sponsor.setTextColor(getResources().getColor(R.color.white));
				my_interest.setTextColor(getResources().getColor(
						R.color.user_center_select_text));
				my_join.setTextColor(getResources().getColor(R.color.white));

				if(interest_flag){
					getData("my_interest", GlobleConstant.MY_INTEREST,
							interest_pagesize);
					interest_flag = false;
				}
				
				break;
			
			}
		}
	}
}
